package robotAi

import xhhx.network.C2sMsg

class SequenceAction<T>(vararg robotActions: RobotAction<T>) : RobotAction<T>() {
    private var actions: MutableList<RobotAction<T>> = mutableListOf()
    private var selectedIndex = 0
    private var selectedAction: RobotAction<T>? = null

    init {
        for ((i, action) in robotActions.withIndex()) {
            action.nodeIndex = i
            action.parentAction = this
            actions.add(action)
        }
        selectedIndex = 0
    }

    override fun GetType(): NodeType {
        return CONTAINER
    }

    override fun GetDescription(): String {
        return "[序列节点 $selectedIndex]"
    }

    override fun Run(t: T): ActionResult {
        var result = FAILED

        var act = selectedAction
        if (act != null) {
            result = act.Run(t)
            if (result == FAILED) {
                actions[selectedIndex] = act.Reset()
                selectedAction = null
                return result
            }

            if (result == RUNNING) {
                return result
            }

            actions[selectedIndex] = act.Reset()
            selectedAction = null
            selectedIndex++

        }

        while (selectedIndex < actions.size) {
            act = actions[selectedIndex]
            result = act.Run(t)
            if (result == FAILED) {
                actions[selectedIndex] = act.Reset()
                selectedAction = null
                return result
            }

            if (result == RUNNING) {
                selectedAction = act
                return result
            }

            actions[selectedIndex] = act.Reset()
            selectedAction = null
            selectedIndex++
        }

        return SUCCESS
    }

    override fun ReceiveMessage(msg: C2sMsg): ActionResult {
        var result = RUNNING
        var act = selectedAction
        if (act == null) {
            return result
        }

        result = act.ReceiveMessage(msg)

        if (result == FAILED) {
            actions[selectedIndex] = act.Reset()
            selectedAction = null
            return result
        }

        if (result == RUNNING) {
            return result
        }

        actions[selectedIndex] = act.Reset()
        selectedAction = null
        selectedIndex++

        return RUNNING
    }

    override fun Reset(): RobotAction<T> {
        selectedIndex = 0
        selectedAction = null
        return this
    }
}

